package edu.hnu.cloudflightserver.server;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantLock;

import edu.hnu.cloudflight.android.domain.FlightWarnModel;

public class FlightWarnServer {

	private static ConcurrentLinkedQueue<FlightWarnModel> requestServerList = new ConcurrentLinkedQueue<FlightWarnModel>();
	private static ConcurrentLinkedQueue<FlightWarnModel> requestServerListTemp = new ConcurrentLinkedQueue<FlightWarnModel>();
	private static ExecutorService serverThreadPools = Executors.newFixedThreadPool(4);
	private static int frequency = 30;
	private static boolean isDoTask;
	private static ReentrantLock lock = new ReentrantLock();

	public static void init() {
		new Timer().schedule(new TimerTask() {

			@Override
			public void run() {
				doTask();

			}
		}, frequency * 60 * 1000);
	}

	public static void doTask() {
		isDoTask = true;
		for (int i = 0; i < 4; i++) {
			serverThreadPools.execute(new Runnable() {
				public void run() {
					if (!requestServerList.isEmpty()) {

						FlightWarnModel task = requestServerList.poll();
						System.out.println(Thread.currentThread().getName() + "begin do task and task is " + task.flightNum);
						try {
							Thread.sleep(5 * 1000);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
						System.out.println(Thread.currentThread().getName() + "has done task ");
					} else {
						lock.lock();
						isDoTask = false;
						requestServerList = requestServerListTemp;
						requestServerListTemp.clear();
						lock.unlock();
					}

				}
			});
		}
	}

	public static boolean addTask(FlightWarnModel fwm) {
		if (isDoTask) {
			return requestServerListTemp.add(fwm);
		} else {
			return requestServerList.add(fwm);
		}

	}

	public static int getTaskCount() {
		return requestServerList.size();
	}

}
